package org.example.business.endpoint.http.event.connection;

import lombok.extern.slf4j.Slf4j;
import org.example.business.endpoint.http.HttpSocket;
import org.example.business.endpoint.http.HttpSocketManager;
import org.example.objevent.event.EventActor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class SocketLifeCycleActor implements EventActor<SocketLifeCycleEvent> {

    @Autowired
    private HttpSocketManager socketManager;

    @Override
    public String getWatchEvent() {
        return "HTTP_LIFE_CYCLE";

    }

    @Override
    public void act(SocketLifeCycleEvent event) {
        log.info("处理连接事件 [type: {}, socket: {}]", event.getType().name(), event.getSocket().toString());

        if(SocketLifeCycleEvent.Type.CONNECT == event.getType()){

            HttpSocket httpSocket = event.getSocket();

            if(null == socketManager.getSocket(httpSocket.getSocketKey())){

                httpSocket.setState(HttpSocket.State.Connected);

                socketManager.addSocket(event.getSocket());

            }

        }

        if(SocketLifeCycleEvent.Type.CLOSE == event.getType()){

            HttpSocket httpSocket = event.getSocket();

            HttpSocket managedSocket = socketManager.getSocket(httpSocket.getSocketKey());

            if(null != managedSocket){

                managedSocket.setState(HttpSocket.State.Closed);

                socketManager.delSocket(managedSocket);

            }

        }

    }

}
